"""
执行引擎 V3.0
完全重新设计，实现完整的增删改查操作
"""

import json
import time
import os
import struct
from typing import Dict, Any, List, Optional, Tuple, Set, DefaultDict
from enum import Enum
try:
    from ..storage.page_storage_v3 import PageStorageV3, RecordSerializer
except ImportError:
    from storage.page_storage_v3 import PageStorageV3, RecordSerializer

#枚举定义
class JoinType(Enum):
    INNER = "INNER"
    LEFT = "LEFT"
    RIGHT = "RIGHT"
    FULL = "FULL"
    CROSS = "CROSS"

class AggregateFunc(Enum):
    AVG = "AVG"
    SUM = "SUM"
    COUNT = "COUNT"
    MAX = "MAX"
    MIN = "MIN"

# 查询处理器
class QueryProcessor:
    """处理复杂查询的处理器（集成到执行引擎中）"""
    
    def __init__(self, engine: 'ExecutionEngineV3'):
        self.engine = engine  # 关联执行引擎，用于访问存储和目录
        self.ast = None
    
    def process(self, ast: Dict[str, Any]) -> Dict[str, Any]:
        """处理查询AST，生成结构化查询计划"""
        self.ast = ast
        query_type = ast.get('type')
        
        if query_type == 'SELECT':
            return self._process_select(ast)
        elif query_type == 'SELECT_WITH_CTE':
            return self._process_select_with_cte(ast)
        elif query_type == 'SET_OPERATION':
            return self._process_set_operation(ast)
        else:
            return ast  # 其他类型（如CREATE TABLE）直接返回
    
    def _process_select(self, ast: Dict[str, Any]) -> Dict[str, Any]:
        """处理SELECT查询的核心逻辑"""
        # 处理from_clause，支持两种情况：
        # 1. 原始计划直接包含table_name字段（来自SQLCompiler）
        # 2. 原始计划包含from_clause列表
        from_clause = ast.get('from_clause', [])
        if 'table_name' in ast and not from_clause:
            # 如果有table_name但没有from_clause，创建一个简单的from_clause
            from_clause = [{'type': 'TABLE', 'name': ast['table_name']}]
        
        return {
            'type': 'SELECT',
            'columns': self._process_select_list(ast.get('columns', [])),
            'from_clause': self._process_from_clause(from_clause),
            'where_clause': self._process_condition(ast.get('where_clause')),
            'group_by': self._process_group_by(ast.get('group_by')),
            'having': self._process_condition(ast.get('having')),
            'order_by': self._process_order_by(ast.get('order_by')),
            'limit': ast.get('limit'),
            'offset': ast.get('offset'),
            'distinct': ast.get('distinct', False)
        }
    
    def _process_select_with_cte(self, ast: Dict[str, Any]) -> Dict[str, Any]:
        """处理带CTE的SELECT查询"""
        cte_list = [self._process_cte(cte) for cte in ast.get('cte_list', [])]
        select = self._process(ast.get('select', {}))
        return {'type': 'SELECT_WITH_CTE', 'cte_list': cte_list, 'select': select}
    
    def _process_cte(self, cte: Dict[str, Any]) -> Dict[str, Any]:
        """处理CTE（公共表表达式）"""
        return {
            'name': cte.get('name'),
            'query': self._process(cte.get('query', {})),  # 递归处理子查询
            'alias': cte.get('alias')
        }
    
    def _process_set_operation(self, ast: Dict[str, Any]) -> Dict[str, Any]:
        """处理集合操作（UNION、INTERSECT等）"""
        return {
            'type': 'SET_OPERATION',
            'operation': ast.get('operation'),
            'left': self._process(ast.get('left', {})),
            'right': self._process(ast.get('right', {})),
            'all': ast.get('all', False)
        }
    
    def _process_select_list(self, select_list: Any) -> List[Dict[str, Any]]:
        """处理选择列表（支持列、聚合函数、*）"""
        if isinstance(select_list, dict) and select_list.get('type') == 'ALL_COLUMNS':
            return [{'type': 'ALL_COLUMNS'}]
        
        if not isinstance(select_list, list):
            return []
        
        processed = []
        for item in select_list:
            if isinstance(item, dict):
                if 'expression' in item:
                    processed.append({
                        'type': 'EXPRESSION',
                        'expression': self._process_expression(item['expression']),
                        'alias': item.get('alias')
                    })
                elif 'function' in item:  # 聚合函数（如 AVG(age)）
                    processed.append(self._process_aggregate_function(item))
                else:
                    processed.append({'type': 'COLUMN', 'name': item})
            else:
                processed.append({'type': 'COLUMN', 'name': item})
        
        return processed
    
    def _process_aggregate_function(self, agg_func: Dict[str, Any]) -> Dict[str, Any]:
        """处理聚合函数（如 AVG(age)）"""
        return {
            'type': 'AGGREGATE',
            'function': AggregateFunc(agg_func.get('function').upper()),
            'distinct': agg_func.get('distinct', False),
            'argument': self._process_expression(agg_func.get('argument'))
        }
    
    def _process_from_clause(self, from_clause: Any) -> List[Dict[str, Any]]:
        """处理FROM子句（支持表、JOIN、子查询）"""
        if not isinstance(from_clause, list):
            return []
        
        processed = []
        for item in from_clause:
            if isinstance(item, dict):
                if item.get('type') == 'JOIN':
                    processed.append(self._process_join(item))
                elif item.get('type') == 'TABLE':
                    processed.append({
                        'type': 'TABLE',
                        'name': item.get('name'),
                        'alias': item.get('alias')
                    })
                elif item.get('type') == 'SUBQUERY':
                    processed.append({
                        'type': 'SUBQUERY',
                        'query': self._process(item.get('query', {})),
                        'alias': item.get('alias')
                    })
            else:
                processed.append({'type': 'TABLE', 'name': item})
        
        return processed
    
    def _process_join(self, join: Dict[str, Any]) -> Dict[str, Any]:
        """处理JOIN操作（支持INNER、LEFT等）"""
        return {
            'type': 'JOIN',
            'join_type': JoinType(join.get('join_type', 'INNER').upper()),
            'left': self._process_from_clause([join.get('left')])[0],
            'right': self._process_from_clause([join.get('right')])[0],
            'condition': self._process_condition(join.get('condition'))
        }
    
    def _process_condition(self, condition: Any) -> Optional[Dict[str, Any]]:
        """处理条件表达式（比较、逻辑、IN等）"""
        if condition is None:
            return None
        
        if not isinstance(condition, dict):
            return condition
        
        condition_type = condition.get('type')
        
        if condition_type == 'COMPARISON':
            return {
                'type': 'COMPARISON',
                'operator': condition.get('operator'),
                'left': self._process_expression(condition.get('left')),
                'right': self._process_expression(condition.get('right'))
            }
        elif condition_type == 'LOGICAL':
            if condition.get('operator') == 'NOT':
                return {
                    'type': 'LOGICAL',
                    'operator': 'NOT',
                    'operand': self._process_condition(condition.get('operand'))
                }
            else:
                return {
                    'type': 'LOGICAL',
                    'operator': condition.get('operator'),
                    'left': self._process_condition(condition.get('left')),
                    'right': self._process_condition(condition.get('right'))
                }
        elif condition_type == 'CONDITION_IN':
            return {
                'type': 'CONDITION_IN',
                'expression': self._process_expression(condition.get('expression')),
                'subquery': self._process(condition.get('subquery', {})),
                'not': condition.get('not', False)
            }
        else:
            return condition  # 其他条件类型（如EXISTS）后续扩展
    
    def _process_expression(self, expression: Any) -> Any:
        """处理表达式（列、字面量、算术运算等）"""
        if expression is None:
            return None
        
        if not isinstance(expression, dict):
            return expression
        
        expression_type = expression.get('type')
        
        if expression_type == 'ARITHMETIC':
            return {
                'type': 'ARITHMETIC',
                'operator': expression.get('operator'),
                'left': self._process_expression(expression.get('left')),
                'right': self._process_expression(expression.get('right'))
            }
        elif expression_type == 'FUNCTION':
            return {
                'type': 'FUNCTION',
                'name': expression.get('name'),
                'arguments': [self._process_expression(arg) for arg in expression.get('arguments', [])]
            }
        elif expression_type == 'CASE':
            return {
                'type': 'CASE',
                'base_expression': self._process_expression(expression.get('base_expression')),
                'when_clauses': [self._process_when_clause(when) for when in expression.get('when_clauses', [])],
                'else': self._process_expression(expression.get('else'))
            }
        else:
            return expression  # 其他表达式类型（如CAST）后续扩展
    
    def _process_group_by(self, group_by: Any) -> Optional[List[Dict[str, Any]]]:
        """处理GROUP BY子句"""
        if group_by is None:
            return None
        
        if not isinstance(group_by, list):
            return [{'type': 'COLUMN', 'name': group_by}]
        
        return [{'type': 'COLUMN', 'name': col} for col in group_by]
    
    def _process_order_by(self, order_by: Any) -> Optional[List[Dict[str, Any]]]:
        """处理ORDER BY子句"""
        if order_by is None:
            return None
        
        if not isinstance(order_by, list):
            return None
        
        processed = []
        for item in order_by:
            if isinstance(item, dict):
                processed.append({
                    'type': 'ORDER_COLUMN',
                    'column': self._process_expression(item.get('column')),
                    'direction': item.get('direction', 'ASC')
                })
            else:
                processed.append({
                    'type': 'ORDER_COLUMN',
                    'column': {'type': 'COLUMN', 'name': item},
                    'direction': 'ASC'
                })
        
        return processed

# 执行引擎
class ExecutionEngineV3:
    """执行引擎 V3.0"""
    
    def __init__(self, data_dir: str = "data"):
        """初始化执行引擎"""
        self.storage = PageStorageV3(data_dir)
        self.catalog_file = os.path.join(data_dir, "catalog.json")
        self.catalog = self._load_catalog()
        self.query_processor = QueryProcessor(self)
        
        # 确保数据目录存在
        os.makedirs(data_dir, exist_ok=True)
    
    def _load_catalog(self) -> Dict[str, Any]:
        """加载系统目录"""
        if os.path.exists(self.catalog_file):
            try:
                with open(self.catalog_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                pass
        return {}
    
    def _save_catalog(self):
        """保存系统目录"""
        try:
            with open(self.catalog_file, 'w', encoding='utf-8') as f:
                json.dump(self.catalog, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"保存系统目录失败: {e}")
    
    def execute_plan(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行执行计划"""
        try:
            if plan['type'] == 'CREATE_TABLE':
                return self._execute_create_table(plan)
            elif plan['type'] == 'INSERT':
                return self._execute_insert(plan)
            elif plan['type'] == 'SELECT':
                return self._execute_select(plan)
            elif plan['type'] == 'DELETE':
                return self._execute_delete(plan)
            elif plan['type'] == 'UPDATE':
                return self._execute_update(plan)
            elif plan['type'] == 'DROP_TABLE':
                return self._execute_drop_table(plan)
            else:
                return {'success': False, 'error': f"不支持的执行计划类型: {plan['type']}"}
        except Exception as e:
            return {'success': False, 'error': f"执行错误: {str(e)}"}
    
    def _execute_create_table(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行CREATE TABLE"""
        table_name = plan['table_name']
        schema = plan['schema']
        
        # 检查表是否已存在
        if table_name in self.catalog:
            return {'success': False, 'error': f"表 '{table_name}' 已存在"}
        
        # 创建表结构
        table_info = {
            'schema': schema,
            'created_at': self._get_current_time(),
            'record_count': 0,
            'pages': []
        }
        
        # 保存到目录
        self.catalog[table_name] = table_info
        self._save_catalog()
        
        return {
            'success': True,
            'message': f"表 '{table_name}' 创建成功",
            'table_name': table_name
        }
    
    def _execute_insert(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行INSERT"""
        table_name = plan['table_name']
        columns = plan['columns']
        values = plan['values']
        
        # 检查表是否存在
        if table_name not in self.catalog:
            return {'success': False, 'error': f"表 '{table_name}' 不存在"}
        
        table_info = self.catalog[table_name]
        schema = table_info['schema']
        
        # 构建记录
        record = {}
        for i, col_name in enumerate(columns):
            record[col_name] = values[i]['value']
        
        # 序列化记录
        serialized_record = RecordSerializer.serialize_record(record, schema)
        
        # 查找可用的页面
        page_id = self._find_available_page(table_name, len(serialized_record))
        
        # 读取页面数据
        page_data = self.storage.read_page(page_id)
        
        # 在页面中查找空闲位置
        offset = self._find_free_space_in_page(page_data, len(serialized_record))
        
        if offset == -1:
            return {'success': False, 'error': "页面空间不足"}
        
        # 写入记录
        page_data = bytearray(page_data)
        page_data[offset:offset+len(serialized_record)] = serialized_record
        
        # 更新页面头部信息（记录位置和大小）
        self._update_page_header(page_data, offset, len(serialized_record))
        
        # 写回页面
        self.storage.write_page(page_id, bytes(page_data))
        
        # 更新表信息
        table_info['record_count'] += 1
        self._save_catalog()
        
        return {
            'success': True,
            'message': f"成功插入1条记录到表 '{table_name}'",
            'affected_rows': 1
        }
    
    # def _execute_select(self, plan: Dict[str, Any]) -> Dict[str, Any]:
    #     """执行SELECT"""
    #     table_name = plan['table_name']
    #     columns = plan['columns']
    #     where_clause = plan.get('where_clause')
        
    #     # 检查表是否存在
    #     if table_name not in self.catalog:
    #         return {'success': False, 'error': f"表 '{table_name}' 不存在"}
        
    #     table_info = self.catalog[table_name]
    #     schema = table_info['schema']
        
    #     # 获取表的页面
    #     page_ids = self.storage.get_table_pages(table_name)
    #     if not page_ids:
    #         return {
    #             'success': True,
    #             'data': [],
    #             'columns': columns if columns != '*' else list(schema['columns'].keys()),
    #             'row_count': 0
    #         }
        
    #     # 读取所有记录
    #     all_records = []
    #     for page_id in page_ids:
    #         page_data = self.storage.read_page(page_id)
    #         records = self._extract_records_from_page(page_data, schema)
    #         all_records.extend(records)
        
    #     # 应用WHERE条件
    #     if where_clause:
    #         filtered_records = []
    #         for record in all_records:
    #             condition_result = self._evaluate_condition(where_clause, record)
    #             if condition_result:
    #                 filtered_records.append(record)
    #         all_records = filtered_records
        
    #     # 选择列
    #     if columns == '*':
    #         selected_records = all_records
    #         selected_columns = list(schema['columns'].keys())
    #     else:
    #         selected_records = []
    #         for record in all_records:
    #             selected_record = {col: record.get(col) for col in columns}
    #             selected_records.append(selected_record)
    #         selected_columns = columns
        
    #     return {
    #         'success': True,
    #         'data': selected_records,
    #         'columns': selected_columns,
    #         'row_count': len(selected_records)
    #     }
    
    def _execute_select(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行SELECT（支持复杂查询：JOIN、GROUP BY、聚合函数等）"""
        # 1. 预处理：解析AST，生成结构化查询计划
        processed_plan = self.query_processor.process(plan)
        
        # 2. 执行查询（根据处理后的计划分派到具体逻辑）
        if processed_plan.get('type') != 'SELECT':
            return {'success': False, 'error': "无效的SELECT计划"}
        
        # 3. 处理基础查询（无JOIN、无聚合）
        if not processed_plan.get('group_by') and not any(
            col.get('type') == 'AGGREGATE' for col in processed_plan.get('columns', [])
        ):
            return self._execute_simple_select(processed_plan)
        
        # 4. 处理复杂查询（JOIN、聚合等）
        return self._execute_complex_select(processed_plan)
    
    def _execute_simple_select(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行简单SELECT（无JOIN、无聚合）"""
        # 兼容不同格式的SELECT计划
        if 'from_clause' in plan and plan['from_clause'] and isinstance(plan['from_clause'], list):
            table_name = plan['from_clause'][0]['name']
        elif 'table_name' in plan:
            table_name = plan['table_name']
        else:
            return {'success': False, 'error': "未找到表名信息"}
        
        columns = plan['columns']
        where_clause = plan.get('where_clause')
        order_by = plan.get('order_by', [])
        limit = plan.get('limit')
        offset = plan.get('offset', 0)
        
        # 检查表是否存在
        if table_name not in self.catalog:
            return {'success': False, 'error': f"表 '{table_name}' 不存在"}
        
        table_info = self.catalog[table_name]
        schema = table_info['schema']
        
        # 获取表的页面
        page_ids = self.storage.get_table_pages(table_name)
        if not page_ids:
            return {
                'success': True,
                'data': [],
                'columns': self._get_columns_for_select(columns, schema),
                'row_count': 0
            }
        
        # 读取所有记录并过滤
        all_records = []
        for page_id in page_ids:
            page_data = self.storage.read_page(page_id)
            records = self._extract_records_from_page(page_data, schema)
            all_records.extend(records)
        
        if where_clause:
            filtered_records = [
                rec for rec in all_records
                if self._evaluate_condition(where_clause, rec)
            ]
            all_records = filtered_records
        
        # 应用ORDER BY
        if order_by:
            for order_expr in reversed(order_by):  # 从右到左应用排序
                # 处理两种情况：column是对象或直接是列名
                if isinstance(order_expr['column'], dict) and 'name' in order_expr['column']:
                    column_name = order_expr['column']['name']
                else:
                    column_name = order_expr['column']
                
                direction = order_expr.get('direction', 'ASC')
                
                all_records.sort(key=lambda x: x.get(column_name), reverse=(direction == 'DESC'))
        
        # 应用OFFSET和LIMIT
        if offset > 0:
            all_records = all_records[offset:]
        
        if limit is not None:
            all_records = all_records[:limit]
        
        # 选择列
        selected_columns = self._get_columns_for_select(columns, schema)
        selected_records = [
            {col: rec.get(col) for col in selected_columns} if columns != '*'
            else rec for rec in all_records
        ]
        
        return {
            'success': True,
            'data': selected_records,
            'columns': selected_columns,
            'row_count': len(selected_records)
        }
    
    def _execute_complex_select(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行复杂SELECT（含JOIN、GROUP BY、聚合函数等）"""
        # 示例：处理JOIN（简化逻辑，实际需完善）
        if plan.get('from_clause') and any(
            clause['type'] == 'JOIN' for clause in plan['from_clause']
        ):
            return self._execute_join(plan)
        
        # 示例：处理GROUP BY聚合（简化逻辑，实际需完善）
        if plan.get('group_by'):
            return self._execute_aggregation(plan)
        
        return {'success': False, 'error': "不支持的复杂查询类型"}
    
    def _execute_join(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行JOIN操作（简化版：仅支持INNER JOIN）"""
        # 提取JOIN信息
        join_clause = next(
            (c for c in plan['from_clause'] if c['type'] == 'JOIN'), None
        )
        if not join_clause:
            return {'success': False, 'error': "未找到JOIN子句"}
        
        left_table = join_clause['left']['name']
        right_table = join_clause['right']['name']
        condition = join_clause['condition']
        
        # 检查表是否存在
        for table in [left_table, right_table]:
            if table not in self.catalog:
                return {'success': False, 'error': f"表 '{table}' 不存在"}
        
        # 读取左右表数据
        left_records = self._get_table_records(left_table)
        right_records = self._get_table_records(right_table)
        
        # 执行INNER JOIN
        joined_records = []
        for l_rec in left_records:
            for r_rec in right_records:
                if self._evaluate_condition(condition, {**l_rec, **r_rec}):
                    joined_records.append({**l_rec, **r_rec})
        
        # 选择列（简化处理：返回所有列）
        columns = plan['columns']
        selected_columns = self._get_columns_for_select(columns, left_records[0] if left_records else {})
        selected_records = [
            {col: rec.get(col) for col in selected_columns} for rec in joined_records
        ]
        
        return {
            'success': True,
            'data': selected_records,
            'columns': selected_columns,
            'row_count': len(selected_records)
        }
    
    def _execute_aggregation(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行GROUP BY聚合（简化版：仅支持COUNT、AVG）"""
        # 提取GROUP BY列和聚合函数
        group_by_cols = [col['name'] for col in plan['group_by']]
        aggregates = [
            col for col in plan['columns'] 
            if col.get('type') == 'AGGREGATE'
        ]
        
        # 读取表数据
        table_name = plan['from_clause'][0]['name']
        records = self._get_table_records(table_name)
        
        # 分组
        groups = DefaultDict(list)
        for rec in records:
            group_key = tuple(rec[col] for col in group_by_cols)
            groups[group_key].append(rec)
        
        # 计算聚合值
        result = []
        for group_key, group_recs in groups.items():
            row = dict(zip(group_by_cols, group_key))
            for agg in aggregates:
                func = agg['function'].value
                col = agg['argument']['name']
                values = [rec[col] for rec in group_recs if col in rec]
                
                if func == 'COUNT':
                    row[f"{func}()"] = len(values)
                elif func == 'AVG':
                    row[f"{func}({col})"] = sum(values)/len(values) if values else None
            result.append(row)
        
        # 选择列
        selected_columns = [col['name'] for col in group_by_cols] + [
            f"{agg['function']()}({agg['argument']['name']})" for agg in aggregates
        ]
        selected_records = [
            {col: rec[col] for col in selected_columns} for rec in result
        ]
        
        return {
            'success': True,
            'data': selected_records,
            'columns': selected_columns,
            'row_count': len(selected_records)
        }
    
    # ------------------------------ 辅助方法 ------------------------------
    def _get_table_records(self, table_name: str) -> List[Dict[str, Any]]:
        """获取表的所有记录（简化实现）"""
        page_ids = self.storage.get_table_pages(table_name)
        records = []
        for page_id in page_ids:
            page_data = self.storage.read_page(page_id)
            records.extend(self._extract_records_from_page(page_data, self.catalog[table_name]['schema']))
        return records
    
    def _get_columns_for_select(self, columns: List[Any], schema: Dict) -> List[str]:
        """获取SELECT的列名列表"""
        if columns == ['*']:
            return list(schema['columns'].keys())
        return [col['name'] if isinstance(col, dict) and col.get('type') == 'COLUMN' else col for col in columns]
        
    def _execute_delete(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行DELETE"""
        table_name = plan['table_name']
        where_clause = plan.get('where_clause')
        
        # 检查表是否存在
        if table_name not in self.catalog:
            return {'success': False, 'error': f"表 '{table_name}' 不存在"}
        
        table_info = self.catalog[table_name]
        schema = table_info['schema']
        
        # 获取表的页面
        page_ids = self.storage.get_table_pages(table_name)
        if not page_ids:
            return {
                'success': True,
                'message': "没有记录被删除",
                'affected_rows': 0
            }
        
        deleted_count = 0
        
        # 处理每个页面
        for page_id in page_ids:
            page_data = self.storage.read_page(page_id)
            page_data = bytearray(page_data)
            
            # 获取页面中的记录信息
            record_infos = self._get_page_record_infos(page_data)
            
            # 标记要删除的记录
            records_to_delete = []
            for i, record_info in enumerate(record_infos):
                if record_info['deleted']:
                    continue
                
                # 读取记录
                record_data = page_data[record_info['offset']:record_info['offset']+record_info['size']]
                record = RecordSerializer.deserialize_record(record_data, schema)
                
                # 检查WHERE条件
                if where_clause:
                    # 有WHERE条件，只删除满足条件的记录
                    if self._evaluate_condition(where_clause, record):
                        records_to_delete.append(i)
                else:
                    # 没有WHERE条件，删除所有记录
                    records_to_delete.append(i)
            
            # 删除记录
            for i in reversed(records_to_delete):
                self._mark_record_deleted(page_data, record_infos[i])
                deleted_count += 1
            
            # 写回页面
            self.storage.write_page(page_id, bytes(page_data))
        
        # 更新表信息
        table_info['record_count'] = max(0, table_info['record_count'] - deleted_count)
        self._save_catalog()
        
        return {
            'success': True,
            'message': f"成功删除 {deleted_count} 条记录",
            'affected_rows': deleted_count
        }
    
    def _execute_update(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行UPDATE"""
        table_name = plan['table_name']
        assignments = plan['assignments']
        where_clause = plan.get('where_clause')

        print(f"WHERE条件: {where_clause}")  # 添加调试输出
        print(f"赋值列表: {assignments}")  # 添加调试输出

        # 检查表是否存在
        if table_name not in self.catalog:
            return {'success': False, 'error': f"表 '{table_name}' 不存在"}
        
        table_info = self.catalog[table_name]
        schema = table_info['schema']
        
        # 获取表的页面
        page_ids = self.storage.get_table_pages(table_name)
        if not page_ids:
            return {
                'success': True,
                'message': "没有记录被更新",
                'affected_rows': 0
            }
        
        updated_count = 0
        
        # 处理每个页面
        for page_id in page_ids:
            page_data = self.storage.read_page(page_id)
            page_data = bytearray(page_data)
            
            # 获取页面中的记录信息
            record_infos = self._get_page_record_infos(page_data)
            
            # 更新记录
            for record_info in record_infos:
                if record_info['deleted']:
                    continue
                
                # 读取记录
                record_data = page_data[record_info['offset']:record_info['offset']+record_info['size']]
                record = RecordSerializer.deserialize_record(record_data, schema)
                
                # 检查WHERE条件
                if not where_clause or self._evaluate_condition(where_clause, record):
                    # 更新记录
                    for assignment in assignments:
                        col_name = assignment['column']
                        # new_value = assignment['value']['value']
                        new_value = self._evaluate_expression(assignment['value'], record)
                        record[col_name] = new_value
                    
                    # 重新序列化记录
                    new_record_data = RecordSerializer.serialize_record(record, schema)
                    
                    # 检查新记录是否能放入原位置
                    if len(new_record_data) <= record_info['size']:
                        # 直接替换
                        page_data[record_info['offset']:record_info['offset']+len(new_record_data)] = new_record_data
                        # 更新记录大小
                        self._update_record_size(page_data, record_info, len(new_record_data))
                    else:
                        # 需要重新分配空间
                        # 标记原记录为删除
                        self._mark_record_deleted(page_data, record_info)
                        # 在页面末尾添加新记录
                        new_offset = self._find_free_space_in_page(page_data, len(new_record_data))
                        if new_offset != -1:
                            page_data[new_offset:new_offset+len(new_record_data)] = new_record_data
                            self._add_record_to_page_header(page_data, new_offset, len(new_record_data))
                    
                    updated_count += 1
            
            # 写回页面
            self.storage.write_page(page_id, bytes(page_data))
        
        return {
            'success': True,
            'message': f"成功更新 {updated_count} 条记录",
            'affected_rows': updated_count
        }
    
    def _execute_drop_table(self, plan: Dict[str, Any]) -> Dict[str, Any]:
        """执行DROP TABLE"""
        table_name = plan['table_name']
        
        # 检查表是否存在
        if table_name not in self.catalog:
            return {'success': False, 'error': f"表 '{table_name}' 不存在"}
        
        # 删除表的所有页面
        self.storage.remove_table_pages(table_name)
        
        # 从目录中删除表
        del self.catalog[table_name]
        self._save_catalog()
        
        return {
            'success': True,
            'message': f"表 '{table_name}' 删除成功"
        }
    
    def _find_available_page(self, table_name: str, record_size: int) -> int:
        """查找可用的页面"""
        page_ids = self.storage.get_table_pages(table_name)
        
        # 检查现有页面是否有足够空间
        for page_id in page_ids:
            page_data = self.storage.read_page(page_id)
            if self._has_space_in_page(page_data, record_size):
                return page_id
        
        # 分配新页面
        new_page_id = self.storage.allocate_page()
        self.storage.add_page_to_table(table_name, new_page_id)
        
        # 初始化页面头部
        page_data = bytearray(self.storage.page_size)
        self._initialize_page_header(page_data)
        self.storage.write_page(new_page_id, bytes(page_data))
        
        return new_page_id
    
    def _has_space_in_page(self, page_data: bytes, record_size: int) -> bool:
        """检查页面是否有足够空间"""
        # 简化的空间检查：页面头部占用64字节
        header_size = 64
        used_space = self._get_used_space_in_page(page_data)
        return (len(page_data) - header_size - used_space) >= record_size
    
    def _get_used_space_in_page(self, page_data: bytes) -> int:
        """获取页面中已使用的空间"""
        # 从页面头部读取记录信息
        record_count = struct.unpack('<I', page_data[0:4])[0]
        used_space = 0
        
        for i in range(record_count):
            offset = 8 + i * 12  # 每个记录信息12字节
            if offset + 8 <= len(page_data):
                size = struct.unpack('<I', page_data[offset+4:offset+8])[0]
                used_space += size
        
        return used_space
    
    def _find_free_space_in_page(self, page_data: bytes, record_size: int) -> int:
        """在页面中查找空闲空间"""
        header_size = 64
        used_space = self._get_used_space_in_page(page_data)
        
        if (len(page_data) - header_size - used_space) >= record_size:
            return header_size + used_space
        
        return -1
    
    def _initialize_page_header(self, page_data: bytearray):
        """初始化页面头部"""
        # 记录数量
        struct.pack_into('<I', page_data, 0, 0)
        # 页面状态
        struct.pack_into('<I', page_data, 4, 1)  # 1表示活跃
    
    def _update_page_header(self, page_data: bytearray, offset: int, size: int):
        """更新页面头部，添加记录信息"""
        record_count = struct.unpack('<I', page_data[0:4])[0]
        
        # 添加新记录信息
        info_offset = 8 + record_count * 12
        struct.pack_into('<I', page_data, info_offset, offset)
        struct.pack_into('<I', page_data, info_offset + 4, size)
        struct.pack_into('<I', page_data, info_offset + 8, 0)  # 0表示未删除
        
        # 更新记录数量
        struct.pack_into('<I', page_data, 0, record_count + 1)
    
    def _get_page_record_infos(self, page_data: bytes) -> List[Dict[str, Any]]:
        """获取页面中的记录信息"""
        record_count = struct.unpack('<I', page_data[0:4])[0]
        record_infos = []
        
        for i in range(record_count):
            offset = 8 + i * 12
            if offset + 12 <= len(page_data):
                record_offset = struct.unpack('<I', page_data[offset:offset+4])[0]
                record_size = struct.unpack('<I', page_data[offset+4:offset+8])[0]
                deleted = struct.unpack('<I', page_data[offset+8:offset+12])[0]
                
                record_infos.append({
                    'offset': record_offset,
                    'size': record_size,
                    'deleted': bool(deleted)
                })
        
        return record_infos
    
    def _mark_record_deleted(self, page_data: bytearray, record_info: Dict[str, Any]):
        """标记记录为删除"""
        # 找到记录信息的位置并标记为删除
        record_count = struct.unpack('<I', page_data[0:4])[0]
        
        for i in range(record_count):
            offset = 8 + i * 12
            if offset + 12 <= len(page_data):
                record_offset = struct.unpack('<I', page_data[offset:offset+4])[0]
                if record_offset == record_info['offset']:
                    struct.pack_into('<I', page_data, offset + 8, 1)  # 1表示已删除
                    break
    
    def _update_record_size(self, page_data: bytearray, record_info: Dict[str, Any], new_size: int):
        """更新记录大小"""
        record_count = struct.unpack('<I', page_data[0:4])[0]
        
        for i in range(record_count):
            offset = 8 + i * 12
            if offset + 12 <= len(page_data):
                record_offset = struct.unpack('<I', page_data[offset:offset+4])[0]
                if record_offset == record_info['offset']:
                    struct.pack_into('<I', page_data, offset + 4, new_size)
                    break
    
    def _add_record_to_page_header(self, page_data: bytearray, offset: int, size: int):
        """添加记录到页面头部"""
        self._update_page_header(page_data, offset, size)
    
    def _extract_records_from_page(self, page_data: bytes, schema: Dict[str, Any]) -> List[Dict[str, Any]]:
        """从页面中提取记录"""
        record_infos = self._get_page_record_infos(page_data)
        records = []
        
        for record_info in record_infos:
            if not record_info['deleted']:
                record_data = page_data[record_info['offset']:record_info['offset']+record_info['size']]
                record = RecordSerializer.deserialize_record(record_data, schema)
                records.append(record)
        
        return records
    
    def _evaluate_condition(self, condition: Dict[str, Any], record: Dict[str, Any]) -> bool:
        """评估WHERE条件"""
        if condition['type'] == 'COMPARISON':
            left = self._evaluate_expression(condition['left'], record)
            right = self._evaluate_expression(condition['right'], record)
            operator = condition['operator']

            if left is None or right is None:
                return False
            
            if operator == '=':
                return left == right
            elif operator == '!=' or operator == '<>':
                return left != right
            elif operator == '<':
                return left < right
            elif operator == '<=':
                return left <= right
            elif operator == '>':
                return left > right
            elif operator == '>=':
                return left >= right
            else:
                return False
        
        elif condition['type'] == 'LOGICAL':
            operator = condition['operator']
            if operator == 'AND':
                return (self._evaluate_condition(condition['left'], record) and
                        self._evaluate_condition(condition['right'], record))
            elif operator == 'OR':
                return (self._evaluate_condition(condition['left'], record) or
                        self._evaluate_condition(condition['right'], record))
            elif operator == 'NOT':
                return not self._evaluate_condition(condition['operand'], record)
        
        elif condition['type'] == 'BETWEEN':
            expr = self._evaluate_expression(condition['expression'], record)
            lower = self._evaluate_expression(condition['lower'], record)
            upper = self._evaluate_expression(condition['upper'], record)
            
            # 检查值是否在范围之内（包含边界）
            return lower <= expr <= upper
        
        return False
    
    def _evaluate_expression(self, expression: Dict[str, Any], record: Dict[str, Any]) -> Any:
        """评估表达式"""
        if expression['type'] == 'COLUMN':
            return record.get(expression['name'])
        elif expression['type'] in ['NUMBER', 'STRING', 'BOOLEAN']:
            return expression['value']
        elif expression['type'] == 'ARITHMETIC':
            left = self._evaluate_expression(expression['left'], record)
            right = self._evaluate_expression(expression['right'], record)
            operator = expression['operator']
            
            if operator == '+':
                return left + right
            elif operator == '-':
                return left - right
            elif operator == '*':
                return left * right
            elif operator == '/':
                return left / right if right != 0 else 0
            elif operator == '%':
                return left % right if right != 0 else 0
        
        return None
    
    def _get_current_time(self) -> str:
        """获取当前时间字符串"""
        return str(int(time.time()))
    
    def get_catalog(self) -> Dict[str, Any]:
        """获取系统目录"""
        return self.catalog
    
    def print_catalog(self):
        """打印系统目录"""
        print("系统目录:")
        print("-" * 60)
        
        if not self.catalog:
            print("目录为空")
            return
        
        for table_name, table_info in self.catalog.items():
            print(f"表: {table_name}")
            print(f"  创建时间: {table_info['created_at']}")
            print(f"  记录数量: {table_info['record_count']}")
            print(f"  页面数量: {len(table_info['pages'])}")
            print("  列:")
            for col_name, col_info in table_info['schema']['columns'].items():
                col_type = col_info['type']['type']
                if col_info['type'].get('length'):
                    col_type += f"({col_info['type']['length']})"
                print(f"    {col_name}: {col_type}")
            print()
    
    def shutdown(self):
        """关闭执行引擎"""
        print("🔄 关闭执行引擎...")
        
        # 刷新所有脏页到磁盘
        if hasattr(self.storage, 'flush_all'):
            self.storage.flush_all()
        
        print("✅ 执行引擎已关闭")

def main():
    """测试执行引擎"""
    engine = ExecutionEngineV3("test_data")
    
    # 测试创建表
    create_plan = {
        'type': 'CREATE_TABLE',
        'table_name': 'tst1',
        'schema': {
            'columns': {
                'id': {'type': {'type': 'int'}},
                'name': {'type': {'type': 'varchar'}},
                'age': {'type': {'type': 'int'}}
            }
        }
    }
    
    result = engine.execute_plan(create_plan)
    print(f"创建表结果: {result}")
    
    # 测试插入数据
    insert_plan = {
        'type': 'INSERT',
        'table_name': 'tst1',
        'columns': ['id', 'name', 'age'],
        'values': [
            {'type': 'NUMBER', 'value': 1},
            {'type': 'STRING', 'value': 'Alice'},
            {'type': 'NUMBER', 'value': 25}
        ]
    }
    
    result = engine.execute_plan(insert_plan)
    print(f"插入数据结果: {result}")
    
    # 测试查询数据
    select_plan = {
        'type': 'SELECT',
        'table_name': 'tst1',
        'columns': '*',
        'where_clause': {
            'type': 'COMPARISON',
            'operator': '>',
            'left': {'type': 'COLUMN', 'name': 'age'},
            'right': {'type': 'NUMBER', 'value': 20}
        }
    }
    
    result = engine.execute_plan(select_plan)
    print(f"查询数据结果: {result}")
    
    # 打印系统目录
    engine.print_catalog()
    
    # 关闭执行引擎
    engine.shutdown()

if __name__ == "__main__":
    import os
    import struct
    main()